package com.example.demo.config;

import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.creator.DefaultDataSourceCreator;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DataSourceProperty;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.example.demo.exception.BusinessException;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import javax.sql.DataSource;
import java.util.Map;

/**
 * 动态数据源配置
 * @author Administrator
 */
@Configuration
@RequiredArgsConstructor
public class DynamicDataSource extends DynamicRoutingDataSource {

    private final DefaultDataSourceCreator defaultDataSourceCreator;

    public DataSource determineDataSource() {
        //获取当前的数据源key 为null默认走master
        String dsKey = DynamicDataSourceContextHolder.peek();
        Map<String, DataSource> dataSources = this.getDataSources();
        if (StringUtils.hasText(dsKey) && !dataSources.containsKey(dsKey)){
            throw new BusinessException("501","不存在的数据源信息!");
        }
        return this.getDataSource(dsKey);
    }

    @Override
    public Map<String, DataSource> getDataSources() {
        return super.getDataSources();
    }

    public void setDataSources(DataSourceProperty dataSourceProperty){
        //创建新的数据源
        DataSource dataSource = defaultDataSourceCreator.createDataSource(dataSourceProperty);
        //获取本地数据源
        Map<String, DataSource> dataSources = this.getDataSources();
        //把添加的数据源存入本地
        dataSources.put(dataSourceProperty.getPoolName(),dataSource);
    }
}
